package com.hfi.security.core.authentication.openid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.security.SocialUserDetailsService;

/**
 * @author ChangLiang
 * @date 2019/8/14
 */
@Configuration
public class OpenIdAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain,
        HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler hfiAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler hfiAuthenticationFailureHandler;

    @Autowired
    private SocialUserDetailsService userDetailsService;

    @Autowired
    private UsersConnectionRepository usersConnectionRepository;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 配置filter和provider
        OpenIdAuthenticationFilter authenticationFilter = new OpenIdAuthenticationFilter();
        authenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        authenticationFilter.setAuthenticationSuccessHandler(hfiAuthenticationSuccessHandler);
        authenticationFilter.setAuthenticationFailureHandler(hfiAuthenticationFailureHandler);

        OpenIdAuthenticationProvider authenticationProvider = new OpenIdAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setUsersConnectionRepository(usersConnectionRepository);

        // 配置验证filter 放到browser项目中

        http.authenticationProvider(authenticationProvider)
                .addFilterAfter(authenticationFilter, UsernamePasswordAuthenticationFilter.class);

    }
}
